package com.zjk.toolkit.dynamic.thread.pool.sdk.trigger.listener;


import com.alibaba.fastjson.JSON;
import com.zjk.toolkit.dynamic.thread.pool.sdk.domain.IDyThreadPoolService;
import com.zjk.toolkit.dynamic.thread.pool.sdk.domain.entity.ThreadPoolEntity;
import com.zjk.toolkit.dynamic.thread.pool.sdk.registry.IRegistry;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.listener.MessageListener;

import java.util.List;

/**
 * 动态线程变更监听
 */
@RequiredArgsConstructor
@Slf4j
public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolEntity> {
    private final IDyThreadPoolService dyThreadPoolService;
    private final IRegistry redisRegistry;

    /**
     * 监听动态线程池配置变更
     */
    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolEntity threadPoolEntity) {
        log.info("动态线程池，调整线程池配置。线程池名称:{} 核心线程数:{} 最大线程数:{}",
                threadPoolEntity.getThreadPoolName(), threadPoolEntity.getPoolSize(), threadPoolEntity.getMaximumPoolSize());
        dyThreadPoolService.updateThreadPool(threadPoolEntity);

        // 变更后report最新数据
        List<ThreadPoolEntity> threadPoolEntityList= dyThreadPoolService.queryThreadPoolList();
        redisRegistry.reportThreadPool(threadPoolEntityList);

        ThreadPoolEntity current = dyThreadPoolService.queryThreadPoolByPoolName(threadPoolEntity.getThreadPoolName());
        redisRegistry.reportThreadPoolConfigParamter(current);
        log.info("动态线程池，上报线程池信息：{}", JSON.toJSONString(threadPoolEntityList));
    }
}
